$(document).ready(function () {

    $("#date-value").val(getFormattedDate())
    $("#laydate-s~div").find('input').val("日")
    queryType()

    layui.use(function () {

        var layer = layui.layer;

        var laydate = layui.laydate;
        table = layui.table;
        form = layui.form;
        // 覆盖实例与销毁实例

        var inst = laydate.render({

            elem: '#date-value',
            theme: ['grid', '#245775'],
            done: function (value) {
                queryParams = {
                    "type": 1,
                    "begin": value
                }
                queryTable()
            }

        });

        form.on("select(filter-demo-laydate-reset)", function (obj) {

            var value = obj.value;

            var options = inst.config;

            var elem = options.elem[0];

            laydate.unbind(options.id);
            $('#date-value').val('')

            if (value == "week") {
                laydate.render({
                    elem: elem,
                    show: true,
                    showBottom: false,
                    value: new Date(),
                    disabledDate: function (date) {
                        return date.getDay() !== 1; // 仅允许选择周一
                    },
                    theme: ['grid', '#245775'],
                    mark: function (ymd, render) {
                        var y = ymd.year;
                        var m = ymd.month;
                        var d = ymd.date;
                        if (new Date(y + '-' + m + '-' + d).getDay() === 1) return render('周一');
                    },
                    weekStart: 1,
                    formatToDisplay: function (value) {
                        if (value) {
                            // 拆分原始值（兼容空值情况）
                            var selectedDate = value.split(' - ')[0];

                            // 解析日期组件
                            var dateParts = selectedDate.split('-');
                            var startDate = new Date(
                                parseInt(dateParts[0]),
                                parseInt(dateParts[1]) - 1, // 月份修正
                                parseInt(dateParts[2])
                            );

                            // 计算结束日期
                            var endDate = new Date(startDate);
                            endDate.setDate(startDate.getDate() + 7);

                            // 自定义格式化函数
                            function formatDate(date) {
                                return [
                                    date.getFullYear(),
                                    (date.getMonth() + 1).toString().padStart(2, '0'),
                                    date.getDate().toString().padStart(2, '0')
                                ].join('-');
                            }
                            curWeek = formatDate(startDate) + ' ~ ' + formatDate(endDate);

                            return formatDate(startDate) + ' ~ ' + formatDate(endDate)
                        }
                    },
                    done: function (value) {
                        queryParams = {
                            "type": 2,
                            "begin": curWeek.split(' ~ ')[0],
                            "end": curWeek.split(' ~ ')[1],
                        }
                        queryTable()

                    }
                });
            } else if (value == "quarter") {
                laydate.render({
                    elem: elem,
                    theme: ['circle', '#245775'],
                    type: "month",
                    show: true,
                    showBottom: false,
                    value: new Date(),
                    id: 'quarter-date',
                    cellRender: function (ymd, render, info) {

                        var m = ymd.month;

                        if (info.type === 'month') {
                            switch (m) {
                                case 1:
                                case 2:
                                case 3:
                                    render("第一季度");
                                    break;
                                case 4:
                                case 5:
                                case 6:
                                    render("第二季度");
                                    break;
                                case 7:
                                case 8:
                                case 9:
                                    render("第三季度");
                                    break;
                                case 10:
                                case 11:
                                case 12:
                                    render("第四季度");
                                    break;

                                default:
                                    break;
                            }
                        }
                    },
                    formatToDisplay: function (value) {
                        switch (new Date(value).getMonth() + 1) {
                            case 1:
                            case 2:
                            case 3:
                                return new Date(value).getFullYear() + '年' + "第一季度"
                            case 4:
                            case 5:
                            case 6:
                                return new Date(value).getFullYear() + '年' + "第二季度"
                            case 7:
                            case 8:
                            case 9:
                                return new Date(value).getFullYear() + '年' + "第三季度"
                            case 10:
                            case 11:
                            case 12:
                                return new Date(value).getFullYear() + '年' + "第四季度"

                            default:
                                break;
                        }
                    },
                    done: function (value) {

                        const [year, month] = value.split('-')

                        var q = null;

                        switch (month) {
                            case "01":
                            case "02":
                            case "03":
                                q = 1;
                                break;
                            case "04":
                            case "05":
                            case "06":
                                q = 2;
                                break;
                            case "07":
                            case "08":
                            case "09":
                                q = 3;
                                break;
                            case "10":
                            case "11":
                            case "12":
                                q = 4;
                                break;
                            default:
                                break;
                        }


                        queryParams = {
                            "type": 4,
                            "begin": year,
                            "end": q
                        }
                        queryTable()

                    }
                });

            } else {
                laydate.render({
                    elem: elem,
                    theme: ['grid', '#245775'],
                    type: value,
                    show: true,
                    value: new Date(),
                    disabledDate: function (date) {
                        return null;
                    },
                    cellRender: function (ymd, render, info) {

                        var m = ymd.month;

                        if (info.type === 'month') {
                            render(m);
                        }
                    },
                    formatToDisplay: function (value) {
                        return value
                    },
                    done: function (res) {

                        switch (value) {
                            case "date":
                                queryParams = {
                                    "type": 1,
                                    "begin": res
                                }
                                break;
                            case "month":
                                queryParams = {
                                    "type": 3,
                                    "begin": res
                                }
                                break;
                            case "year":
                                queryParams = {
                                    "type": 6,
                                    "begin": res
                                }
                                break;

                            default:
                                break;
                        }
                        queryTable()

                    }
                });
            }



        });

        initSubMenu();

    });
})
var queryParams = {
    "type": 1,
    "begin": getFormattedDate()
}
var params = {};//查询条件参数
var form, unit, table;
var drawer;//抽屉实例
var curType = 1;//当前选中考核标准ID
var curWeek = null;

$('.contain-tab-item').click(function (e) {
    $(e.currentTarget).addClass('active').siblings().removeClass('active');

    if ($(e.currentTarget).data().type == 2) {
        $('.choose-date').css('display', 'flex');
        $('.assess-rule').hide();
        queryTable()
    } else {
        $('.choose-date').hide();
        $('.assess-rule').show();
        evaluationList()
    }


})

var typeStr = []
queryType = () => {

    new AjaxChain()
        .setUrl('/assess/rule/select')
        .then(data => {
            typeStr = data;
            evaluationList()

        })
        .send();
}

//查询考核标准类型列表
queryTable = () => {


    layui.use('table', function () {
        var table = layui.table;

        params.status = curType

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , url: ajaxPrefix() + "/assess/record/count/list"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where:
                queryParams

            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "data": res.result //解析数据列表
                };
            }
            , cols: [[
                { field: 'seqNo', title: '序号', align: "center" },
                { field: 'personName', title: '姓名', align: "center" },
                { field: 'professionalTitleDesc', title: '消防救援衔', align: "center" },
                { field: 'workDateDesc', title: '入职日期', align: "center" },
                { field: 'plusDesc', title: '加分事由', align: "center", hide: queryParams.type == 4 || queryParams.type == 6 },
                { field: 'plusScore', title: '累计加分', align: "center" },
                { field: 'minusDesc', title: '减分事由', align: "center", hide: queryParams.type == 4 || queryParams.type == 6 },
                { field: 'minusScore', title: '累计减分', align: "center" },
                { field: 'score', title: '得分', align: "center" }
            ]]
            , height: '#contain-table-list-10'
            // ,skin: 'line' //表格风格
            , even: true
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

    });
}

// 量化考评打分列表

evaluationList = () => {

    layui.use('table', function () {
        let toolWidth = window.innerWidth / 1920
        var table = layui.table;

        params.status = curType

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , url: ajaxPrefix() + "/assess/record/count/list"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , lineStyle: 'height: ' + $('.contain-tab-item').width() * 2 + ';'
            , where:
            {
                "type": 1,
                "begin": getFormattedDate()
            }

            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "data": res.result //解析数据列表
                };
            }
            , cols: [[
                {
                    field: 'personName', title: '基本信息', align: "center", width: toolWidth * 400,
                    templet: function (d) {

                        return `<ul class="table-ul">
                                    <li><span>序号：</span> ${d.seqNo} </li>
                                    <li><span>姓名：</span> ${d.personName} </li>
                                    <li><span>消防救援衔：</span> ${d.professionalTitleDesc} </li>
                                    <li><span>入职时间：</span> ${d.workDateDesc || '-'} </li>
                                </ul>`;
                    },
                },
                {
                    field: 'plusDesc', title: '加分事由', align: "center",
                    templet: function (d) {

                        return `<div class="table-tool">
                                      ${typeStr.filter(item => item.type == 1).reduce((x, y) => {

                            return x + `<div  data-id="${y.id}" data-personId="${d.personId}" onclick=scoring("${d.personId}",this,${y.score},1) class="score-item plus ${d.plusIds?.includes(y.id) ? "active" : ''}">${y.name + ' +' + y.score}</div>`
                        }, '')
                            }
                                </div>`;
                    },
                },
                {
                    field: 'personName', title: '', align: "center", width: 10,
                    templet: function (d) {
                        return `<div style="color: #243a42;font-size: 0.24rem;">|</div>`;
                    },
                },
                {
                    field: 'minusDesc', title: '减分事由', align: "center",
                    templet: function (d) {

                        return `<div class="table-tool">
                                      ${typeStr.filter(item => item.type == 2).reduce((x, y) => {
                            return x + `<div data-id="${y.id}" data-personId="${d.personId}" onclick=scoring("${d.personId}",this,${y.score},2) class="score-item minus ${d.minusIds?.includes(y.id) ? "active" : ''}">${y.name + ' -' + y.score}</div>`
                        }, '')
                            }
                                </div>`;
                    },
                },
                {
                    field: 'score', title: '当前分数', align: "center", width: toolWidth * 250,
                    templet: function (d) {
                        return `<div class="table-score" id="score-${d.personId}">${d.score}</div>`;
                    },
                }

            ]]
            , height: '#contain-table-list-10'
            // ,skin: 'line' //表格风格
            , even: true
            , done: function (res, curr, count) {

                // $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

    });
}

scoring = (personId, t, score, type) => {
    $(t).toggleClass('active');

    var ruleIds = $(`.score-item.active[data-personId="${personId}"]`).map(function () {
        return $(this).attr('data-id'); // 强制返回字符串
    }).get();

    new AjaxChain()
        .setMethod('post')
        .setUrl('/assess/record/save')
        .setData(JSON.stringify(
            {
                "personId": personId,
                "ruleIds": ruleIds
            }
        ))
        .then(data => {

            const $scoreElement = $('#score-' + personId);
            const currentScore = parseFloat($scoreElement.text()) || 0;
            const isActive = $(t).hasClass('active');
            const sign = (type === 1 && isActive) || (type !== 1 && !isActive) ? 1 : -1;
            const newScore = currentScore + (sign * score);
            $scoreElement.text(newScore)

        })
        .send();
}



// 导出
function exportData(type) {

    var exportP = queryParams;
    exportP.sessionId = JSON.parse(localStorage.getItem('sessionId'))

    const params = new URLSearchParams(exportP);

    if (type == 1) {
        window.location.href = `/rest/fstation/assess/record/word/export?${params}`;

    } else {
        window.location.href = `/rest/fstation/assess/record/excel/export?${params}`;

    }

}


function getFormattedDate(format = 'YYYY-MM-DD') {
    const date = new Date();
    const y = date.getFullYear();
    const m = date.getMonth() + 1;
    const d = date.getDate();

    const pad = (n) => n.toString().padStart(2, '0');

    switch (format) {
        case 'YYYY-MM-DD':
            return `${y}-${pad(m)}-${pad(d)}`;
        case 'MM/DD/YYYY':
            return `${pad(m)}/${pad(d)}/${y}`;
        case 'CN':
            return `${y}年${pad(m)}月${pad(d)}日`;
        default:
            return date.toISOString(); // 默认ISO格式
    }
}





// 规则节点弹窗列表
queryNodeList = () => {

    layer.open({
        title: `<div style="height: 100%;display: flex;align-items: center;">
                    <div class="table-edit layui-btn" onclick=addNewNodes(1)> 
                        <img src="../static/img/report.png">新增规则
                    </div>
                </div>`,
        type: 1,
        area: ['80%', '80%'],
        shade: 0.3,
        move:false,
        shadeClose: false,
        id: 'rd-offset',
        end: function (elem) {

            queryType()

        },
        success: function (layero, index, that) {

            queryNodeTable()

        },
        content: `<table id="node-table" lay-filter="node-table"></table>`
    });

}

//新增规则弹窗
addNewNodes = (id, type) => {

    layer.open({
        type: 1,
        area: ['40%', '40%'],
        resize: false,
        shadeClose: true,
        title: "新增规则",
        content: `<form class="layui-form layui-form-pane" id="node-form" lay-filter="nodeForm" action="">
                    <div class="form-item">
                        <label class="layui-form-label">规则类型</label>
                        <div class="layui-input-block">
                         <select name="type" lay-verify="required">
                              <option value=""></option>
                              <option value="1">加分</option>
                              <option value="2">减分</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">规则名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" lay-affix="clear" lay-verify="required" placeholder="请输入"  class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">分值</label>
                        <div class="layui-input-block">
                            <input type="text" name="score" lay-affix="clear" lay-verify="required" placeholder="请输入"  class="layui-input">
                        </div>
                    </div>
                    <div class="form-item pane-tool">
                        <div class="layui-btn layui-edit-submit" lay-submit  lay-filter="node-edit">确认</div>
                    </div>
                </form>`,
        success: function (layero, index, that) {
            form.render();

            // form.val('nodeForm', res);

            form.on('submit(node-edit)', function (data) {
                var field = data.field;


                saveNode(field, index)

                return false;
            });
        },
    });

}



// 加载规则列表
queryNodeTable = () => {


    table.render({
        elem: '#node-table'
        , text: {
            none: '暂无数据'
        }
        , method: 'get'
        , url: ajaxPrefix() + "/assess/rule/list"
        , headers: {
            SessionId: JSON.parse(localStorage.getItem('sessionId'))
        }
        , where: {
            pageSize: 10,
            type: ''
        }
        , parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.status == 200 ? 0 : 1, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.result.total, //解析数据长度
                "data": res.result.data
            };
        }
        , request: {
            pageName: 'pageNum' //页码的参数名称，默认：page
            ,
            limitName: 'pageSize' //每页数据量的参数名，默认：limit
        }
        , cols: [
            [ //表头
                {
                    field: 'typeDesc',
                    title: '规则类型',
                    align: 'center',
                    sort: true
                }, {
                    field: 'name',
                    title: '规则名称',
                    align: 'center',
                }, {
                    field: 'score',
                    title: '分值',
                    align: 'center'
                }, {
                    field: 'createTime',
                    title: '创建时间',
                    templet: function (d) {
                        return d.createTime == undefined ? '-' : d.createTime.substring(0, 19)
                    },
                    align: 'center'
                },
                {
                    title: '操作',
                    width: 120,
                    align: 'center',
                    templet: function (d) {
                        return `<div class="table-tool ">
                                    <div onclick='ruleDel("${d.id}")' class="table-del layui-btn">
                                     <img src="../static/img/del.png">删除
                                    </div>
                                </div>`
                    },
                }
            ]
        ]
        , height: 'full'
        // ,skin: 'line' //表格风格
        , even: true
        , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            groups: 3 //只显示 1 个连续页码
            , first: false //不显示首页
            , last: false //不显示尾页
        }
    });


    layui.form.on('switch(table-status)', function (obj) {

        var id = this.value;
        new AjaxChain()
            .setUrl('/audio/use')
            .setMethod('post')
            .setData(JSON.stringify({
                id: id,
                status: (obj.elem.checked ? 1 : 2)
            }))
            .then(data => {
                layer.msg('操作成功', { icon: 1, time: 1500 });
            })
            .catch(err => {
                console.error('请求异常:', err);
            })
            .send();


    });
}


// 删除规则
function ruleDel(id) {

    layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

        new AjaxChain()
            .setUrl('/assess/rule/delete')
            .setData({ id: id })
            .then(data => {
                layer.msg('删除成功', { icon: 1, time: 1500 });
                queryNodeTable()
            })
            .catch(err => {
                console.error('请求异常:', err);
            })
            .send();
    });

}


// 保存规则信息接口
saveNode = (params, index) => {
    new AjaxChain()
        .setUrl('/assess/rule/save')
        .setMethod('post')
        .setData(JSON.stringify(
            params
        ))
        .then(data => {
            if (index) {
                layer.close(index);
            }

            layer.msg('配置成功', { icon: 1, time: 2000 });
            queryNodeTable()
        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();
}


